package cn.edu.imnu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Slf4j
@Component
public class JwtTokenUtil {
//    @Value("${jwt.secret}")
    private static String secret = "123456";
    @Value("${jwt.expire-time}")
    private static long expireTime;

    public static String createToken(Map<String, Object> payload) {
        return JWT.create()
                .withExpiresAt(new Date(System.currentTimeMillis() + expireTime * 1000))
                .withPayload(payload)
                .sign(Algorithm.HMAC256(secret));
    }

    public static boolean verifyToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.warn("JWT验证失败: {}", e.getMessage());
            return false;
        }
    }

    public static Map<String, Object> getTokenPayload(String token) {
        return JWT.decode(token).getClaim("payload").asMap();
    }
}

